
package com.ziq.zcamp.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.SpanUtils
import com.ziq.base.base.BaseDialog
import com.ziq.base.extension.*
import com.ziq.zcamp.R
import com.ziq.zcamp.activities.ActivitiesDetailsViewModel
import com.ziq.zcamp.bean.activities.ActivitiesTicketsInfo
import com.ziq.zcamp.databinding.DialogActivitiesPriceTypeBinding
import com.ziq.zcamp.databinding.ItemActivitiesPriceTypeBinding
import com.ziq.zcamp.util.TimeUtil
import com.ziq.zcamp.view.StatusView
import java.text.DecimalFormat
import java.util.*

class ActivitiesPriceTypeDialog(context: Context, val mViewModel: ActivitiesDetailsViewModel) : BaseDialog(context) {

    private val binding: DialogActivitiesPriceTypeBinding by binding()
    private val mAdapter by lazy { Adapter {
        binding.btNext.isEnabled = it
    } }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.decorView?.let {
            window?.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE or WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        }
        binding.root
        binding.list.adapter = mAdapter
        binding.list.layoutManager = GridLayoutManager(context,2)

        binding.btNext.isEnabled = false

        binding.btNext.click {
            val info = mAdapter.selectedTicket()
            if (info!= null){
                mViewModel.selectedTicketType(info)
            }else{
                Toast.makeText(context,context.getString(R.string.activities_choose_price_type),Toast.LENGTH_SHORT).show()
            }
        }
        setAnimateView(binding.root)
    }

    override fun show() {
        super.show()
        requestData()
    }

    private fun requestData(){
        binding.btNext.isEnabled = false
        mAdapter.choice = -1
        mViewModel.obtainTicketInfo()
        binding.statusView.setStatus(
            StatusView.LOADING
        )
        binding.list.visibility = View.GONE
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setTicketData(list :MutableList<ActivitiesTicketsInfo>){
        if (list.isNullOrEmpty()){
            binding.statusView.setStatus(
                StatusView.NO_DATA,
                isCenter = false,
                marginTop = 42.dp,
                imgSrc = R.drawable.pic_no_content_order,
                imgWidth = 235.dp,
                imgHeight = 151.dp,
                msg = context.getString(R.string.activities_price_type_empty)
            )
        }else{
            binding.statusView.setStatus(
                StatusView.IDLE
            )
            mAdapter.setTicketList(list)
            mAdapter.notifyDataSetChanged()
            binding.list.visibility = View.VISIBLE
        }
    }

    fun showStatusError(){
        binding.statusView.setStatus(
            StatusView.NET_ERROR,
            isCenter = false,
            marginTop = 42.dp,
            updateActionBtn = { btn ->
                btn.click {
                    requestData()
                }
            })
        binding.list.visibility = View.GONE
    }

    override fun initWidth(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    override fun initGravity(): Int {
        return Gravity.BOTTOM or Gravity.CENTER
    }

    private class Adapter(val choiceChange : (isChoice : Boolean)->Unit) : RecyclerView.Adapter<BindingViewHolder<ItemActivitiesPriceTypeBinding>>(){
        var list: MutableList<ActivitiesTicketsInfo> = mutableListOf()
        var choice = -1

        fun setTicketList(list : MutableList<ActivitiesTicketsInfo>){
            this.list = list
        }

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): BindingViewHolder<ItemActivitiesPriceTypeBinding> {
            return createBindingViewHolder(parent)
        }

        override fun onBindViewHolder(
            holder: BindingViewHolder<ItemActivitiesPriceTypeBinding>,
            position: Int
        ) {
            val item = list[position]
            val binding = ItemActivitiesPriceTypeBinding.bind(holder.itemView)
            binding.tvActivitiesPriceTypeName.text = item.name
            if (!item.price_range.isNullOrEmpty()){
                val max = item.price_range?.maxOrNull()
                val min = item.price_range?.minOrNull()
                val str: String = if (max == min){
                    val string = DecimalFormat("0.00").format((max?:0) / 100f)
                    string
                }else{
                    val maxStr = DecimalFormat("0.00").format((max?:0) / 100f)
                    val minStr = DecimalFormat("0.00").format((min?:0) / 100f)
                    "$minStr-$maxStr"
                }

                SpanUtils.with(binding.tvActivitiesPriceTypePrice)
                    .append("￥").setFontSize(10.dp)
                    .append(str)
                    .create()
            }
            binding.tvActivitiesPriceTypeEmpty.visibility = if (item.ticket_status != 1) View.VISIBLE else View.GONE
            when(item.ticket_status){
                2->{
                    binding.tvActivitiesPriceTypeEmpty.text = holder.itemView.context.getString(R.string.activities_sold_out)
                    item.apply {
                        val str =
                            "起订：${TimeUtil.yyyy_MM_dd_SLASH_FORMATTER.format(Date(start_time!!.toLong() * 1000))}"
                        binding.tvActivitiesPriceTypeTime.text = str
                    }
                }
                3->{
                    binding.tvActivitiesPriceTypeEmpty.text = holder.itemView.context.getString(R.string.activities_time_out)
                    item.apply {
                        val str =
                            "起订：${TimeUtil.yyyy_MM_dd_SLASH_FORMATTER.format(Date(start_time!!.toLong() * 1000))}"
                        binding.tvActivitiesPriceTypeTime.text = str
                    }
                }
                else->{
                    item.apply {
                        if (start_time != null && end_time != null){
                            if (TimeUtil.isSameYear((start_time!!.toLong()*1000),(end_time!!.toLong() * 1000))){
                                val str = "起订：${TimeUtil.yyyy_MM_dd_SLASH_FORMATTER.format(Date(start_time!!.toLong()*1000))}～${
                                    TimeUtil.MM_dd_SLASH_FORMATTER.format(
                                        Date(end_time!!.toLong()*1000)
                                    )}"
                                binding.tvActivitiesPriceTypeTime.text = str
                            }else{
                                val str = "起订：${TimeUtil.yyyy_MM_dd_SLASH_FORMATTER.format(Date(start_time!!.toLong()*1000))}～${
                                    TimeUtil.yyyy_MM_dd_SLASH_FORMATTER.format(
                                        Date(end_time!!.toLong()*1000)
                                    )}"
                                binding.tvActivitiesPriceTypeTime.text = str
                            }
                        }else if (start_time != null){
                            val str = "起订：${TimeUtil.yyyy_MM_dd_SLASH_FORMATTER.format(Date(start_time!!.toLong()*1000))}"
                            binding.tvActivitiesPriceTypeTime.text = str
                        }else{
                            binding.tvActivitiesPriceTypeTime.text = "--:--"
                        }
                    }
                }
            }
            if (position == choice){
                binding.shadowLayout.setStrokeWidth((1.5F).dp)
                //        app:hl_shadowColor="#000000"
                binding.shadowLayout.setShadowColor(Color.parseColor("#000000"))
                binding.shadowLayout.setStrokeColor(holder.itemView.context.resources.getColor(R.color.color_af8b6c))
            }
            else{
                binding.shadowLayout.setStrokeWidth(0F)
                binding.shadowLayout.setShadowColor(Color.parseColor("#00000000"))
                binding.shadowLayout.setStrokeColor(holder.itemView.context.resources.getColor(R.color.white))
            }
            binding.shadowLayout.click {
                if (choice == position) {
                    choice = -1
                    notifyItemChanged(holder.bindingAdapterPosition)
                }else{
                    if (item.ticket_status!=1){
                        return@click
                    }
                    val lastChoice = choice
                    choice = holder.bindingAdapterPosition
                    notifyItemChanged(lastChoice)
                    notifyItemChanged(choice)
                }
                choiceChange.invoke(choice != -1)
            }
        }

        override fun getItemCount(): Int {
            return list.size
        }

        fun selectedTicket():ActivitiesTicketsInfo?{
            return if (choice in 0 until list.size){
                list[choice]
            }else{
                null
            }
        }

    }

}